<?php

namespace app\merchant\controller\goods;

use app\merchant\controller\Base;
use app\merchant\model\Category as CategoryModel;

/**
 * 商品分类类
 * Class Category
 * @package app\merchant\controller\goods
 */
class Category extends Base
{

    /**
     * 商品分类列表
     * @return mixed
     */
    public function index()
    {
        $model = new CategoryModel;
        $list = $model->getCacheTree();
        return $this->renderSuccess(compact('list'),"查询成功");

    }


    /**
     * 添加商品分类
     * @return array|mixed
     */
    public function add()
    {
        $model = new CategoryModel;

        if ($model->add($this->postData())) {
            return $this->renderSuccess([],'添加成功');
        }
        return $this->renderError([],$model->getError() ?: '添加失败');
    }


    /**
     * 商品分类详情
     * @return array|mixed
     */
    public function detail()
    {
        $param = $this->postData();
        if(!isset($param['category_id']) || empty($param['category_id'])){
            return $this->renderError([],'参数错误');
        }
        $model = CategoryModel::get($param['category_id'],['image']);
        if(!$model){
            return $this->renderError([],'该分类不存在，请刷新重试');
        }
        return $this->renderSuccess(compact('model'));
    }



    /**
     * 编辑商品分类
     * @param $category_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $param = $this->postData();

        if(!isset($param['category_id']) || empty($param['category_id'])){
            return $this->renderError([],'参数失败');
        }

        //详情
        $model = CategoryModel::get($param['category_id'],['image']);
        if(!$model){
            return $this->renderError([],'该分类不存在，请刷新重试');
        }

        // 更新记录
        if ($model->edit($param)) {
            return $this->renderSuccess([],'更新成功');
        }
        return $this->renderError([],$model->getError() ?: '更新失败');
    }


    /**
     * 删除商品分类
     * @param $category_id
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        $param = $this->postData();

        if(!isset($param['category_id']) || empty($param['category_id'])){
            return $this->renderError([],'参数失败');
        }

        $model = CategoryModel::get($param['category_id']);

        if(!$model){
            return $this->renderError([],'该分类不存在，请刷新重试');
        }

        if (!$model->remove($param['category_id'])) {
            return $this->renderError([],$model->getError() ?: '删除失败');
        }
        return $this->renderSuccess([],'删除成功');
    }





}
